import 'package:flutter/material.dart';
import 'package:flutter_food/core/ext/int_extension.dart';
import 'package:flutter_food/core/model/meal_model.dart';

class MealDetailContent extends StatelessWidget {
  final MealModel _meal;

  MealDetailContent(this._meal);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          _buildBannerImage(),
          _buildCellTitle(context, '制作材料'),
          _buildMaterialsList(context),
          _buildCellTitle(context, '制作步骤'),
          _buildSteps(context),
        ],
      ),
    );
  }

  Widget _buildBannerImage() {
    // Column会按照交叉轴居中对齐，由于图片是网络图片默认无位置，Column会先找一个确定宽度的Widget作为其宽度，并居中对齐
    // 当图片加载完毕，并且图片宽度为全屏，此时会按照全屏居中对齐，页面会重新调整一下
    // 所以预先设置宽度，防止页面重新定位
    return Container(
      width: double.infinity,
      child: Image.network(_meal.imageUrl),
    );
  }

  // 材料列表
  Widget _buildMaterialsList(BuildContext context) {
    return _buildListViewContainer(
        child: ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: _meal.ingredients.length,
      itemBuilder: (ctx, index) {
        return Card(
          elevation: 5.px,
          color: Theme.of(context).accentColor,
          child: Padding(
            padding: EdgeInsets.all(8.px),
            child: Text(
              _meal.ingredients[index],
              style: Theme.of(context).textTheme.bodyText2,
            ),
          ),
        );
      },
    ));
  }

  Widget _buildSteps(BuildContext context) {
    return _buildListViewContainer(
        child: ListView.separated(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      itemCount: _meal.steps.length,
      separatorBuilder: (ctx, index) {
        return Divider();
      },
      itemBuilder: (ctx, index) {
        return ListTile(
          leading: CircleAvatar(
            child: Text(
              '#${index + 1}',
              style: TextStyle(color: Colors.white),
            ),
          ),
          title: Text(
            _meal.steps[index],
          ),
        );
      },
    ));
  }

  // 通用标题
  Widget _buildCellTitle(BuildContext context, String title) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.px),
      child: Text(
        title,
        style: Theme.of(context)
            .textTheme
            .headline6
            .copyWith(fontWeight: FontWeight.bold),
      ),
    );
  }

  // ListView通用卡片背景
  Widget _buildListViewContainer({BuildContext context, Widget child}) {
    return Container(
      padding: EdgeInsets.all(12.px),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.px),
        border: Border.all(color: Colors.grey),
      ),
      margin: EdgeInsets.symmetric(horizontal: 16.px),
      child: child,
    );
  }
}
